<template>
    <view class="verification-list">
        <!-- 全新的头部设计 -->
        <view class="header">
            <view class="title">酒券核销管理中心</view>
            <view class="search-bar">
                <view class="search-input">
                    <u-search
                        v-model="searchKeyword"
                        placeholder="搜索联系人/商品名称"
                        :show-action="false"
                        @search="handleSearch"
                        @clear="handleClearSearch"
                    ></u-search>
                </view>
                <view class="filter-btn" @click="showFilter = true">
                    <u-icon name="list" color="#1890ff" size="30"></u-icon>
                </view>
            </view>
        </view>
        
        <!-- 筛选抽屉 -->
        <u-popup v-model="showFilter" mode="right" width="80%">
            <view class="filter-panel">
                <view class="filter-header">
                    <text class="filter-title">高级筛选</text>
                    <u-icon name="close" size="30" @click="showFilter = false"></u-icon>
                </view>
                
                <view class="filter-section">
                    <view class="section-title">时间范围</view>
                    <u-calendar
                        v-model="showCalendar"
                        mode="range"
                        @confirm="dateConfirm"
                    ></u-calendar>
                    <view class="date-range" @click="showCalendar = true">
                        <text>{{ dateRange || '请选择日期范围' }}</text>
                        <u-icon name="calendar" size="28"></u-icon>
                    </view>
                </view>
                
                <view class="filter-buttons">
                    <u-button @click="resetFilter" plain size="medium">重置</u-button>
                    <u-button @click="applyFilter" type="primary" size="medium">应用筛选</u-button>
                </view>
            </view>
        </u-popup>

        <!-- Order Lists with animation -->
        <mescroll-uni
            top="180rpx"
            ref="scroll"
            @init="mescrollInit"
            :up="{
                auto: true,
                page: {
                    num: 0,
                    size: 10
                },
                noMoreSize: 5,
                textLoading: '努力加载中...',
                textNoMore: '-- 已经到底啦 --',
                empty: {
                    icon: '/static/images/empty/order.png',
                    tip: '暂无核销记录~',
                    fixed: true
                },
                onScroll: true
            }"
            @up="upCallback"
            @down="downCallback"
        >
            <view class="order-contain">
                <view
                    class="order animated-item"
                    v-for="orderItem in orderList"
                    :key="orderItem.id"
                    @click="goOrderDetail(orderItem.code)"
                >
                    <!-- Order Header with new design -->
                    <view class="order-header">
                        <view class="order-user">
                            <u-icon name="account" size="28"></u-icon>
                            <text class="order-sn">{{ orderItem.user.nickname }}</text>
                        </view>
                        <view class="order-code">
                            <u-icon name="key" size="24" color="#999"></u-icon>
                            <text>{{ orderItem.code }}</text>
                        </view>
                        <view class="order-status order-status--completed">已核销</view>
                    </view>

                    <!-- Order Main with card style -->
                    <view class="order-main">
                        <view
                            class="goods"
                            v-for="(goodsItem, goodsIndex) in orderItem.liquorCoupon"
                        >
                            <view class="goods-wrap flex">
                                <view class="image">
                                    <u-image
                                        :src="goodsItem.image"
                                        width="160"
                                        height="160"
                                        radius="12"
                                    ></u-image>
                                </view>

                                <view class="m-l-16 line-1">
                                    <!-- 商品名称 -->
                                    <view class="goods-name line-1 m-t-10">{{
                                        goodsItem.name
                                    }}</view>
                                    <!-- 价值和入账信息 -->
                                    <view class="value-info m-t-10">
                                        <view class="value-item">
                                            <text class="label">价值：</text>
                                            <text class="amount value">{{ goodsItem.value }}</text>
                                        </view>
                                        <view class="value-item">
                                            <text class="label">入账：</text>
                                            <text class="amount income">{{ goodsItem.verification_price }}</text>
                                        </view>
                                    </view>
                                    <view class="verification-code m-t-10">
                                        <u-icon name="key" size="24" color="#999"></u-icon>
                                        <text>核销码：{{ orderItem.coupon_sn }}</text>
                                    </view>
                                    <view class="verification-time m-t-10">
                                        <u-icon name="clock" size="24" color="#999"></u-icon>
                                        <text>{{ orderItem.create_time }}</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </mescroll-uni>

        <!-- 全新骨架屏设计 -->
        <view class="skeleton-container" v-if="loading && !isPulling">
            <view class="skeleton-item" v-for="i in 3" :key="i">
                <view class="skeleton-header">
                    <view class="skeleton-avatar skeleton-loading"></view>
                    <view class="skeleton-text skeleton-loading" style="width: 40%"></view>
                    <view class="skeleton-badge skeleton-loading"></view>
                </view>
                <view class="skeleton-content">
                    <view class="skeleton-image skeleton-loading"></view>
                    <view class="skeleton-info">
                        <view class="skeleton-text skeleton-loading" style="width: 90%"></view>
                        <view class="skeleton-price-row">
                            <view class="skeleton-text skeleton-loading" style="width: 40%"></view>
                            <view class="skeleton-text skeleton-loading" style="width: 40%"></view>
                        </view>
                        <view class="skeleton-text skeleton-loading" style="width: 60%"></view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 底部操作按钮区域 -->
        <view class="operation">
            <view
                class="operation-button manual-code"
                @click="showInputCode = true"
            >
                <u-icon name="edit-pen" size="32" color="#666"></u-icon>
                <text>手动输入核销码</text>
            </view>

            <view class="operation-button scan-code" @click="onScanQRCode">
                <u-icon name="scan" size="32" color="#fff"></u-icon>
                <text>扫码核销</text>
            </view>

            <!-- 手动输入核销码MODAL -->
            <u-modal
                ref="uModalInput"
                v-model="showInputCode"
                show-cancel-button
                confirm-text="确定"
                @confirm="inputOrderCode"
                title="手动核销"
                confirmColor="#1890ff"
            >
                <view class="slot-content row-center" style="padding: 40rpx">
                    <u-input
                        type="number"
                        v-model="code"
                        :border="true"
                        placeholder="请输入核销码"
                        style="width: 100%"
                        placeholderStyle="color: #bbb; font-size: 28rpx"
                    />
                </view>
            </u-modal>
        </view>
    </view>
</template>

<script>
import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js'
import { apiVerificationOrderList } from '@/api/order'
import { isWeixinClient } from '@/utils/tools'
import wechath5 from '@/utils/wechath5'

export default {
    name: 'OrderList',
    mixins: [MescrollMixin],

    data() {
        return {
            orderList: [], // 订单列表
            code: '', // 核销码
            showInputCode: false, // 显示(输入核销码)：是 | 否
            loading: true, // 加载状态
            isPulling: false, // 下拉刷新状态
            
            // 搜索和筛选
            searchKeyword: '', // 搜索关键词
            showFilter: false, // 显示筛选抽屉
            showCalendar: false, // 显示日历选择器
            dateRange: '', // 日期范围显示
            startDate: '', // 开始日期
            endDate: '', // 结束日期
            isFiltered: false, // 是否已筛选
            loadTimer: null, // 用于防抖的定时器
        }
    },

    mounted() {
        // 页面加载完成，尝试预取数据
        setTimeout(() => {
            // 模拟加载完成，关闭骨架屏
            setTimeout(() => {
                this.loading = false;
            }, 1500);
        }, 1000);
    },

    methods: {
        // 添加入场动画
        animateItemsIn() {
            const items = document.querySelectorAll('.animated-item');
            items.forEach((item, index) => {
                item.style.animationDelay = `${index * 0.05}s`;
                item.style.animationName = 'none';
                setTimeout(() => {
                    item.style.animationName = 'fadeInUp';
                }, 10);
            });
        },

        // 刷新列表数据 - 增强版
        refreshData() {
            const ref = this.$refs.scroll;
            if (ref) {
                // 显示下拉刷新状态
                this.isPulling = true;
                
                // 重置并触发上拉加载
                ref.mescroll.resetUpScroll();
                
                // 确保状态最终被重置
                setTimeout(() => {
                    this.isPulling = false;
                }, 1000);
            }
        },

        // 下拉刷新回调
        downCallback() {
            this.isPulling = true;
            setTimeout(() => {
                this.isPulling = false;
            }, 1000);
        },

        // 上拉加载更多 - 优化版本
        upCallback({ num, size }) {
            const ref = this.$refs.scroll;
            if (!ref) return;
            
            // 显示加载状态
            if (num === 1) {
                this.loading = true;
                this.orderList = [];
            }
            
            // 构建请求参数，增加搜索和筛选条件
            const params = {
                page_no: num,
                page_size: size,
                keyword: this.searchKeyword.trim() || undefined,
                start_date: this.isFiltered ? this.startDate : undefined,
                end_date: this.isFiltered ? this.endDate : undefined
            };
            
            // 添加防抖，避免快速滚动导致的多次请求
            clearTimeout(this.loadTimer);
            this.loadTimer = setTimeout(() => {
                // 发起请求
                apiVerificationOrderList(params)
                    .then(({ list, count }) => {
                        // 添加数据到列表
                        this.orderList = [...this.orderList, ...list];
                        
                        // 延迟一点时间，让加载动画显示更自然
                        setTimeout(() => {
                            if (num === 1) {
                                this.loading = false;
                            }
                            
                            // 通知mescroll加载完成
                            ref.mescroll.endSuccess(list.length, count > this.orderList.length);
                            
                            // 添加入场动画
                            this.$nextTick(() => {
                                this.animateItemsIn();
                            });
                        }, 300);
                    })
                    .catch((err) => {
                        console.error('加载失败:', err);
                        if (num === 1) {
                            this.loading = false;
                        }
                        ref.mescroll.endErr();
                        uni.showToast({
                            title: '加载失败，请稍后重试',
                            icon: 'none'
                        });
                    });
            }, 200); // 200ms防抖
        },

        // 去订单详情
        goOrderDetail(code) {
            // 添加转场动画
            uni.showLoading({
                title: '正在核销...',
                mask: true
            });
            
            setTimeout(() => {
                uni.hideLoading();
                this.$Router.push({
                    path: '/pages/verification_detail/verification_detail',
                    query: { code }
                });
            }, 600);
        },

        // 扫描二维码
        onScanQRCode() {
            // #ifdef H5
            uni.showToast({ 
                title: 'H5环境暂不支持扫码功能',
                icon: 'none'
            });
            // #endif
            
            // #ifndef H5
            uni.scanCode({
                scanType: ['qrCode'],
                success: (data) => {
                    console.log('扫码成功：', data);
                    if (data.result) {
                        this.goOrderDetail(data.result);
                    }
                },
                fail: (err) => {
                    console.error('扫码失败：', err);
                    uni.showToast({
                        title: '扫码失败，请重试',
                        icon: 'none'
                    });
                }
            });
            // #endif
        },

        // 手动输入核销码
        inputOrderCode() {
            if (!this.code) {
                uni.showToast({
                    title: '请输入核销码',
                    icon: 'none'
                });
                return;
            }
            
            // 添加简单验证
            if (this.code.length < 3) {
                uni.showToast({
                    title: '核销码格式不正确',
                    icon: 'none'
                });
                return;
            }
            
            this.goOrderDetail(this.code);
        },
        
        // 搜索处理
        handleSearch() {
            if (!this.searchKeyword.trim()) return;
            
            // 重置列表并带上搜索参数重新加载
            const ref = this.$refs.scroll;
            if (ref) {
                ref.mescroll.resetUpScroll();
            }
        },
        
        // 清除搜索
        handleClearSearch() {
            this.searchKeyword = '';
            // 重置列表
            const ref = this.$refs.scroll;
            if (ref) {
                ref.mescroll.resetUpScroll();
            }
        },
        
        // 日期确认
        dateConfirm(e) {
            this.startDate = e.startDate;
            this.endDate = e.endDate;
            this.dateRange = `${e.startDate} 至 ${e.endDate}`;
            this.showCalendar = false;
        },
        
        // 重置筛选
        resetFilter() {
            this.startDate = '';
            this.endDate = '';
            this.dateRange = '';
            this.isFiltered = false;
        },
        
        // 应用筛选
        applyFilter() {
            this.isFiltered = !!(this.startDate && this.endDate);
            this.showFilter = false;
            
            // 重置列表并带上筛选参数重新加载
            const ref = this.$refs.scroll;
            if (ref) {
                ref.mescroll.resetUpScroll();
            }
        }
    },

    watch: {
        // 输入核销码弹窗
        showInputCode(val) {
            this.$set(this, 'code', '');
            if (val) {
                // 延迟聚焦，确保键盘弹起
                setTimeout(() => {
                    this.$nextTick(() => {
                        const inputEl = document.querySelector('.u-input__input');
                        if (inputEl) inputEl.focus();
                    });
                }, 300);
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.verification-list {
    display: flex;
    flex-direction: column;
    padding-bottom: 200rpx;
    background-color: #f7f9fc;
    min-height: 100vh;
    position: relative;
}

/* 新的头部样式 */
.header {
    background-color: #ffffff;
    padding: 30rpx 30rpx 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    position: relative;
    z-index: 10;
}

.header .title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #333;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
}

.search-bar .search-input {
    flex: 1;
}

.search-bar .filter-btn {
    margin-left: 20rpx;
    padding: 14rpx;
    background-color: #f5f7fa;
    border-radius: 50%;
}

/* 新的筛选面板样式 */
.filter-panel {
    padding: 40rpx 30rpx;
    height: 100vh;
    background-color: #fff;
}

.filter-panel .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
}

.filter-panel .filter-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.filter-panel .filter-section {
    margin-bottom: 50rpx;
}

.filter-panel .section-title {
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 20rpx;
    color: #333;
}

.filter-panel .date-range {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    border: 1px solid #eee;
    border-radius: 8rpx;
    margin-top: 20rpx;
}

.filter-panel .filter-buttons {
    display: flex;
    justify-content: space-between;
    margin-top: 60rpx;
}

.filter-panel .filter-buttons .u-button {
    flex: 1;
    margin: 0 10rpx;
}

/* 新的订单样式 */
.order-contain {
    padding: 20rpx;
}

.order-contain .order {
    margin-bottom: 30rpx;
    border-radius: 16rpx;
    background-color: #ffffff;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
    overflow: hidden;
    animation: fadeInUp 0.5s ease;
    transition: all 0.3s ease;
}

.order-contain .order:active {
    transform: translateY(4rpx);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.order-contain .order-header {
    display: flex;
    height: 90rpx;
    align-items: center;
    padding: 0 30rpx;
    border-bottom: 1px solid #f5f5f5;
}

.order-contain .order-header .order-user {
    display: flex;
    align-items: center;
}

.order-contain .order-header .order-user .order-sn {
    font-size: 28rpx;
    font-weight: 500;
    margin-left: 10rpx;
}

.order-contain .order-header .order-code {
    margin-left: auto;
    display: flex;
    align-items: center;
}

.order-contain .order-header .order-code text {
    margin-left: 8rpx;
}

.order-contain .order-header .order-status {
    margin-left: auto;
    font-size: 24rpx;
    padding: 6rpx 16rpx;
    border-radius: 30rpx;
}

.order-contain .order-header .order-status--completed {
    background-color: #e6f7ff;
    color: #1890ff;
}

.order-contain .order-main {
    padding: 20rpx;
}

/* 商品信息新样式 */
.goods {
    width: 100%;
}

.goods-wrap {
    width: 100%;
}

.goods-wrap .goods-name {
    color: #333;
    font-size: 28rpx;
    font-weight: 500;
}

.goods-wrap .image {
    flex: 0;
    margin-right: 20rpx;
}

.value-info {
    display: flex;
    justify-content: space-between;
}

.value-info .value-item {
    font-size: 24rpx;
}

.value-info .value-item .label {
    color: #999;
}

.value-info .value-item .amount {
    font-weight: 500;
}

.value-info .value-item .amount.value {
    color: #ff6b00;
}

.value-info .value-item .amount.income {
    color: #ff4d4f;
}

.verification-code {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #999;
}

.verification-code text {
    margin-left: 8rpx;
}

.verification-time {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #999;
}

.verification-time text {
    margin-left: 8rpx;
}

/* 底部操作区新样式 */
.operation {
    position: fixed;
    z-index: 99;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    padding: 20rpx 30rpx 30rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.operation-button {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 90rpx;
    border-radius: 45rpx;
    font-size: 28rpx;
    font-weight: 500;
}

.operation-button.manual-code {
    background-color: #f5f7fa;
    color: #666;
    margin-right: 20rpx;
}

.operation-button.scan-code {
    background-color: #1890ff;
    color: #fff;
}

.operation-button text {
    margin-left: 10rpx;
}

/* 增强版骨架屏 */
@keyframes skeleton-loading {
    0% {
        background-position: 200% 0;
    }
    100% {
        background-position: -200% 0;
    }
}

.skeleton-loading {
    background: linear-gradient(90deg, #f5f5f5 25%, #ebebeb 50%, #f5f5f5 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
}

.skeleton-container {
    padding: 20rpx;
}

.skeleton-item {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.skeleton-header {
    display: flex;
    align-items: center;
    padding-bottom: 24rpx;
    border-bottom: 1px solid #f5f5f5;
}

.skeleton-avatar {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    margin-right: 16rpx;
}

.skeleton-badge {
    width: 100rpx;
    height: 40rpx;
    border-radius: 20rpx;
    margin-left: auto;
}

.skeleton-content {
    display: flex;
    padding-top: 24rpx;
}

.skeleton-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 12rpx;
}

.skeleton-info {
    flex: 1;
    margin-left: 24rpx;
}

.skeleton-price-row {
    display: flex;
    justify-content: space-between;
    margin: 20rpx 0;
}

.skeleton-text {
    height: 32rpx;
    border-radius: 4rpx;
    margin-bottom: 20rpx;
}

/* 入场动画 */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30rpx);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.animated-item {
    animation: fadeInUp 0.5s ease;
}

/* 加载状态样式 */
.mescroll-upwarp {
    min-height: 60rpx;
    padding: 30rpx 0;
    text-align: center;
}

.mescroll-upwarp .upwarp-tip {
    font-size: 24rpx;
    color: #999;
}

.mescroll-upwarp .upwarp-nodata {
    color: #999;
    font-size: 24rpx;
    padding: 20rpx 0;
}

.mescroll-empty {
    padding: 100rpx 0;
}

.mescroll-empty .empty-tip {
    margin-top: 30rpx;
    font-size: 28rpx;
    color: #999;
}
</style>
